#!/usr/bin/env node
import { program } from "commander";
import { PackManager } from "./pack/PackManager";

/**
 * 这段代码是用于设置Node.js环境变量的。具体来说，它将`NODE_TLS_REJECT_UNAUTHORIZED`变量设置为`'1'`。
 * 在Node.js中，这个变量用于控制是否拒绝未经授权的TLS（传输层安全）连接。
 * 将这个值设置为`'0'`可以允许程序接受自签名证书或不安全的连接，而设置为`'1'`则会强制程序只接受经过授权的安全连接。
 */
process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = '1';

/**
 * .option 用于定义程序能够接受的命令行选项
 * .option(flags, description,[defaultVal])
 * flags: 定义选项的短格式和长格式
 * 格式："-p, --path <value>/[pp]"，其中 -p 是短格式，--path 是长格式，<value> 表示该选项需要一个值， [pp]表示值是可选的。
 */
program
    .option("-p, --path <value>", "Cocos项目根目录[Path]")
    .option("-c, --channel <value>", "指定打包对应渠道名称[ChannelName]")
    .option("-v, --version <value>", "设置打包的版本号格式x.x.x")
    .option("-d, --debug", "是否为测试包true:不是测试包,false:测试包", false)
    .option("-b, --bundle", "是否打包App Bundle 安卓需要 [value]=true|false", false)
    .option("-s, --skip", "是否跳过cocos构建工程，直接使用导出工程 [value]=true|false", false)
    .option("-no, --nonotify", "是否跳过钉钉通知")
    .option("-t, --tdesc [pp]", "小游戏后台上传描述，字节微信等", "")
    .option("-bn, --BMSName [pp]", "实名控制的BMSName", "")
    .option("-bv, --BMSVersion [pp]", "实名控制的BMSVersion", "")
    .option("-cp, --compress", "是否压缩资源", "")
    .option("-oc, --obfuscated", "是否混淆", "")
    .option("-rc, --remoteConfig [pp]", "远程配置路径", "")
    .option("-l, --local", "是否本地", "")
    .option("-ddAt, --AtUser [pp]", "钉钉@人", "")
    .option("-pd, --packDesc [pp]", "打包说明", "")
    .option("-ec, --extraCustomParam [pp]", "额外参数", "")
//解析命令行参数，保存在program中用于获取
program.parse(process.argv);


//用于保存自定义参数值
let projectDir = "";
let channel = "";
let isdebug = false;
let version: string | null = null!;
let desc: string = "";
let androidBundle: boolean = false;
let bmsname: string = "";
let bmsversion: string = "";
let atUser: string = "";  //@ 的用户
let packDesc: string = "";

//赋值获取到的值
projectDir = program.getOptionValue("path");
channel = program.getOptionValue("channel");
version = program.getOptionValue("version");
isdebug = program.getOptionValue("debug");
desc = program.getOptionValue("tdesc");
androidBundle = program.getOptionValue("bundle");
bmsname = program.getOptionValue("BMSName");
bmsversion = program.getOptionValue("BMSVersion");
let skip = program.getOptionValue("skip");
let nonotify = program.getOptionValue("nonotify");
let iscompress = program.getOptionValue("compress");
let isoc = program.getOptionValue("obfuscated");
let remoteconfig = program.getOptionValue("remoteConfig");
let islocal = program.getOptionValue("local");
atUser = program.getOptionValue("AtUser");
packDesc = program.getOptionValue("packDesc");
let extraCusParam = program.getOptionValue("extraCustomParam");
//@ts-ignore
global.isSkipBuild = skip;
//@ts-ignore
global.isSkipNotify = !!nonotify;
//@ts-ignore
global.isCompress = !!iscompress;
//@ts-ignore
global.isOc = !!isoc;
//@ts-ignore
global.remoteConfig = (remoteconfig && remoteconfig.length > 0) ? remoteconfig : "";
//@ts-ignore
global.isPackLocal = !!islocal;
//@ts-ignore
global.atUser = atUser;
//@ts-ignore
global.packDesc = packDesc;
//@ts-ignore
global.extraParam = extraCusParam;

console.log('原始参数:', process.argv);
console.log('额外参数 extraCusParam:', {
    //@ts-ignore
    value: global.extraParam,
    //@ts-ignore
    type: typeof global.extraParam
});

if (typeof bmsversion != "boolean") {
    //@ts-ignore
    global.bmsVersion = bmsversion || "";
}

// 使用指定版本号
//@ts-ignore
const isUseReplaceVer = global.extraParam?.split(',')
    .find((item: string) => item.startsWith('Extra_IsUseReplaceVersion='))
    ?.split('=')[1] === 'true';
console.log('isUseReplaceVer:', isUseReplaceVer);
 //@ts-ignore
global.isUseReplaceVer = isUseReplaceVer || false;
//@ts-ignore
if (global.isUseReplaceVer) {
        //@ts-ignore
        const replaceVersion = global.extraParam?.split(',')
            .find((item: string) => item.startsWith('Extra_ReplaceVersion='))
            ?.split('=')[1];

        if (replaceVersion) {
            const replaceInfo = replaceVersion.split(' ');
            const newName = replaceInfo[0];
            const newCode = replaceInfo[1];
            console.log('使用 Extra_ReplaceVersion 替换版本号：', replaceVersion, " ,", newName, " ,", newCode);
            version = newName;
        }
    }
if (projectDir && channel) {
    //@ts-ignore
    global.isUnity = channel.startsWith("Unity");
    PackManager.init(projectDir, channel, isdebug, version!, desc, androidBundle, bmsname, bmsversion);
}

let i = 2;
/*e:
cd e:/project/auto-pack-creator/build
set batcommond=
if %ISDEBUG%==true set batcommond=-d
if %ISBUNDLE%==true set batcommond=%batcommond% -b
if %ISSKIP%==true set batcommond=%batcommond% -s
for %%i in (%PLATFORMS%) do (node ./app.js -p %WORKSPACE% -c %%i -v %VERSION% -t %UPLOAD_DESC% -bn %BMS_NAME% -bv %BMS_VERSION% %batcommond%)*/

/*
batchcommond=""
if test "$ISDEBUG" = "true"; then
    batchcommond="$batchcommond-d"
fi

if test "$ISSKIP" = "true"; then
    batchcommond="$batchcommond -s"
fi
node ./app.js -p $WORKSPACE -c $PLATFORMS -v $VERSION -bv $BMS_VERSION $batchcommond*/